package question5.com.qee.jdbc;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: learning
 * @Package: question5.com.qee.jdbc
 * @ClassName: OriginUserDaoImpl
 * @Description:
 * @Date: 2021/10/18 7:25 下午
 * @Version: 1.0
 */
public class JdbcUserDaoImpl implements UserDao {


    @Override
    public int add(User user) {
        DefaultSession defaultSession = new DefaultSession();
        try {
            Map<String, Object> paramMap = MapUtils.toMap(user.getClass(), user);

            return defaultSession.insert("insert into tb_user(id,name,feature,create_time,update_time) values(#{id},#{name},#{feature},#{createTime},#{updateTime})", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int remove(Long id) {
        DefaultSession defaultSession = new DefaultSession();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", id);
            return defaultSession.update("delete from tb_user where id=#{id}", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(User user) {
        DefaultSession defaultSession = new DefaultSession();
        try {
            Map<String, Object> paramMap = MapUtils.toMap(user.getClass(), user);
            return defaultSession.update("update tb_user set name=#{name}, feature=#{feature}, update_time=#{updateTime}  where id=#{id}", paramMap);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<User> getAll() {
        DefaultSession defaultSession = new DefaultSession();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            return defaultSession.selectList("select * from tb_user", paramMap, User.class);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
